import React, { Component } from 'react';
import {Button, Form, Input, Checkbox, Switch, Spin, Col, Row, Select, message} from 'antd'
import { messages } from "share/common";
const FormItem = Form.Item;
const Group = Checkbox.Group;
const { Option } = Select;
import 'styles/supplier-management/new-consumer-management/edit-frams/edit-frame.scss'
import NewConsumerServer from '../new-consumer-server'
import {connect} from "react-redux";
import enableSupplierService from "containers/supplier-management/overview/enable-service/enable-service.service";

class DidiEditFrame extends Component{

  constructor(props){
    super(props);
    this.state = {
      editData: {},
      loading: false,
      isClicked: false,
      authorizationScope: ['1', '2', '3'],
      companyIDArr: [],
    };
    this.options = [
      { label: messages('supplier.key295')/*员工同步*/, value: '1' },
      { label: messages('supplier.key501')/*订单回传*/, value: '2' },
      { label: messages('supplier.key502')/*开票申请*/, value: '3' }
    ];
  }

  componentWillMount() {
    const { company } = this.props;
    NewConsumerServer(this).getDepSynConfig(company.tenantId).then(res => {
      this.setState({
        companyIDArr: res.data && res.data.length ? res.data.map(i => i.companyId) : [],
      });
    });
  }

  componentWillReceiveProps(nextProps){
    const { params } = nextProps;
    const { data, index } = params;
    const { editData } = this.state;
    if(data && data.length && JSON.stringify(data[index]) !== JSON.stringify(editData)) {
      this.setState({
        editData: JSON.parse(JSON.stringify(data[index]))
      });
    }
  }

  onCancelEdit = () => {
    this.props.close();
    this.props.form.resetFields();
    this.setState({  isClicked: false });
  };

  onChangeCompanyID = value => {
    this.props.form.setFieldsValue({ 'companyId': value });
  };

  onChangeAuthorizationScope = value => {
    console.log('authorizationScope',value);
    this.setState({ authorizationScope: value });
  };

  onAuthorize = () => {
    const { authorizationScope, editData } = this.state;
    const { company, user } = this.props;
    if(authorizationScope.length === 0){
      message.error(messages('supplier.key216')/*请选择授权范围*/);
      return ;
    }
    this.setState({ loading: true });
    let params = {
      "outCompanyId": editData.companyOID,
      "outCompanyName": company.name,
      "outMemberId": user.userOID,
      "authScope": authorizationScope.join('|'),
      "callBack":"applyType=pc"
    };
    enableSupplierService.getToken(editData.companyOID, params).then(resp => {
      this.setState({ loading: false });
      if (resp.data.errno === '0'){
        let token = resp.data.data.open_auth_token;
        window.open(`https://api.es.xiaojukeji.com/openauth/Platform/index?open_auth_token=${token}`);
      }else {
        message.error(resp.data.errmsg);
      }
    })
  };

  onRefresh = () => {
    const { editData } = this.state;
    NewConsumerServer(this).refreshDidiId(editData.companyOID).then(res => {
      this.props.form.setFieldsValue({ 'companyId': res.data ? res.data[0].companyId : null });
    });
  };

  onSubmitEdit = () => {
    const { company } = this.props;
    const { editData } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err){
        const upParams = {
          "vendor": "didi",
          "companyOID": editData.companyOID,
          "tenantId": company.tenantId,
          "data": JSON.stringify(values)
        };
        NewConsumerServer(this).submitDidiData(upParams).then(res => {
          this.props.close(true);
          this.props.form.resetFields();
        });
      }
    })
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { editData, loading, isClicked, companyIDArr } = this.state;
    const { companyCode, companyName, orderPage, enable, companyId } = editData;
    const formLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };
    return (
      <div className='edit-frame'>
        <Spin spinning={loading}>
          <Form>
            <FormItem label={messages('components.key17'/*公司代码*/)} {...formLayout}>
              {
                getFieldDecorator('companyCode',{
                  initialValue: companyCode || '',
                })(
                  <Input disabled />
                )
              }
            </FormItem>
            <FormItem label={messages('components.key18'/*公司名称*/)} {...formLayout}>
              {
                getFieldDecorator('companyName',{
                  initialValue: companyName || '',
                })(
                  <Input disabled />
                )
              }
            </FormItem>
            <Row>
              <Col offset={6} span={16} >
                <Button type="link" icon="plus" style={{ marginLeft: -15 }} onClick={() => this.setState({ isClicked: true })}>
                  {messages('supplier.key503')/*新建滴滴授权*/}
                </Button>
                {
                  !isClicked
                    ?
                    <p style={{ marginBottom: 32, fontSize: 12, color : '#8e8e8e' }} >{messages('supplier.key504')/*首个公司需要进行滴滴授权*/}</p>
                    :
                    <ul style={{paddingLeft: 15, marginBottom: 32, color : '#8e8e8e'}}>
                      <li><span>{messages('supplier.key505')/*选择授权范围*/}：</span><Group style={{display: "inline-block"}} options={this.options} defaultValue={['1', '2', '3']} onChange={this.onChangeAuthorizationScope}/></li>
                      <li><span>{messages('supplier.key296')/*点击*/}<a onClick={this.onAuthorize}>{messages('supplier.key506')/*立即授权*/}</a>， {messages('supplier.key507')/*通过专用链接跳转至滴滴企业平台*/}；{messages('supplier.key508')/*在页面内，新建滴滴账号并授权/授权已有账号*/}</span></li>
                      <li><span>{messages('supplier.key509')/*授权成功后*/}<a onClick={this.onRefresh}>{messages('supplier.key299')/*刷新*/}</a>{messages('supplier.key510')/*回写滴滴ID*/}</span></li>
                    </ul>
                }
              </Col>
            </Row>
            <FormItem label={messages('supplier.key511')/*滴滴 ID*/} {...formLayout} >
              {
                getFieldDecorator('companyId',{
                  initialValue: companyId === '-' ? null : companyId,
                  rules:[
                    { required:true, message:messages('components.key506'/*必填*/) }
                  ]
                })(
                  <Select onChange={this.onChangeCompanyID}>
                    {companyIDArr.map(option => <Option value={option}>{option}</Option>)}
                  </Select>
                )
              }
            </FormItem>
            <FormItem label={messages('supplier.key512')/*订单转换页*/} {...formLayout} extra={messages('supplier.key513')/*个人订单转为企业订单入口，仅限滴滴高级版账户使用*/}>
              {
                getFieldDecorator('orderPage',{
                  initialValue: orderPage === 'true' || false,
                  valuePropName:'checked',
                })(
                  <Switch />
                )
              }
            </FormItem>
            <FormItem label={messages('common.column.status')/*状态*/} {...formLayout}>
              {
                getFieldDecorator('enable',{
                  initialValue: enable === 1 || false,
                  valuePropName:'checked',
                })(
                  <Switch />
                )
              }
            </FormItem>
          </Form>
        </Spin>
        <div className='affix-bottom'>
          <Button onClick={this.onCancelEdit}>
            {messages('common.cancel')/*取消*/}
          </Button>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <Button type="primary"  onClick={this.onSubmitEdit}>
            {messages('common.ok')/*确定*/}
          </Button>
        </div>
      </div>
    )
  }
}

const wrapperDidiEditFrame = Form.create()(DidiEditFrame);

wrapperDidiEditFrame.getEditData = (record, data, index) => {
  return {data, index};
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user
  }
}

export default connect(mapStateToProps)(wrapperDidiEditFrame);


